package bera.lee.memorycard;

import java.text.DecimalFormat;
import java.text.Format;

import bera.lee.memorycard.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

public class BitmapTouch extends Activity {

	protected static final int GUIUPDATEIDENTIFIER = 0x101;

	protected static final int GUIUPDATEIDENTIFIER2 = 0x102;

	/**
	 * 开成功的变成透明
	 */
	protected final Animation an = new AlphaAnimation(1.0f, 0.5f);

	/**
	 * 卡片布局
	 */
	private TableLayout tl;
	private long time ;
	/**
	 * 音乐播放器
	 */
	private MediaPlayer music_card;

	private MediaPlayer music_fail;

	private MediaPlayer music_success;

	/**
	 * 背景音乐
	 */
	// private MediaPlayer music_song;

	/**
	 * 背景音乐
	 */
	// private MediaPlayer music_win;

	/**
	 * 父layout 主要是为了使tablelayout居中
	 */
	private RelativeLayout rl;

	// 当前游戏进行状态 1开始选择第一张牌 2开始选择第二张排
	private int state;

	// 保存每张排
	private BeraCard[] beragroup;

	// x有多少个
	private int xlength;

	// y有多少个
	private int ylength;

	// 卡片值数组
	private int[] cardvalues;

	/**
	 * 默认卡片的图片
	 */
	private int default_cardimage;

	/**
	 * 等待下一张翻开结果的卡片
	 */
	private BeraCard waitcard;

	private BeraCard touchingcard;

	/**
	 * 已经被打开的卡片个数，用来判断游戏结束
	 */
	private int opened_card;

	private Handler mHandler;

	/**
	 * 是否正在操作
	 */
	private boolean isdoing;

	private DbAdapter mDbHelper;

	private long from;

	private long to;

	private boolean start;

	private Format format = new DecimalFormat("0.000");

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		rl = new RelativeLayout(this);
		RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		lp1.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		rl.setBackgroundResource(R.drawable.bg7);
		tl = new TableLayout(this);
		rl.addView(tl, lp1);
		mHandler = new Handler();
		mDbHelper = new DbAdapter(this);
		mDbHelper.open();
		// 初始化运行数据
		initData();
		// 初始化界面数据
		initImage();

		setContentView(rl);

	}

	private void initData() {
		// 初始状态
		state = 1;
		beragroup = new BeraCard[Config.CARD_NUM];
		opened_card = 0;
		waitcard = null;
		isdoing = false;
		start = false;
		time=0;
		default_cardimage = Config.DCARD;
		music_card = MediaPlayer.create(this, R.raw.card);
		music_fail = MediaPlayer.create(this, R.raw.fail);
		music_success = MediaPlayer.create(this, R.raw.success);
		cardvalues = MapUtil.createMap(Config.CARD_NUM, Config.CARD_TYPE);
		if (Config.OPEN_MUSIC) {
			MainMenu.music_song = MediaPlayer.create(this, R.raw.music1);
			MainMenu.music_song.setLooping(true);
			MainMenu.music_song.start();
		}
	}

	private void initImage() {
		switch (Config.CARD_NUM) {
		case 12:
			xlength = 3;
			ylength = 4;
			break;
		case 16:
			xlength = 4;
			ylength = 4;
			break;
		case 20:
			xlength = 4;
			ylength = 5;
			break;
		case 24:
			xlength = 4;
			ylength = 6;
			break;
		case 30:
			xlength = 5;
			ylength = 6;
			break;
		case 36:
			xlength = 6;
			ylength = 6;
			break;
		case 42:
			xlength = 6;
			ylength = 7;
			break;
		case 48:
			xlength = 6;
			ylength = 8;
			break;
		}
		int image_index = 0;
		for (int i = 0; i < ylength; i++) {
			TableRow row = new TableRow(this);
			for (int j = 0; j < xlength; j++) {
				beragroup[image_index] = new BeraCard(this);
				beragroup[image_index].setImageResource(default_cardimage);
				beragroup[image_index].setPadding(0, 0, 0, 0);
				beragroup[image_index].setOnTouchListener(new SimpleListener());
				beragroup[image_index].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT));
				beragroup[image_index].setCard_value(cardvalues[image_index]);
				//调整图片大小
				row.addView(beragroup[image_index], new TableRow.LayoutParams(Config.CARD_SIZE,Config.CARD_SIZE));
				image_index++;
			}
			tl.addView(row, new TableLayout.LayoutParams());
		}

	}

	class BeraCard extends ImageView {
		final Handler mHandler = new Handler();

		final Runnable mUpdateResults = new Runnable() {
			public void run() {
				invalidate(); // 更新视图
			}
		};

		// 卡片当前状态 0关闭 1打开
		private int card_state = 0;

		// 卡片的真实值
		private int card_value;

		/**
		 * @param cardValue
		 *            the card_value to set
		 */
		public void setCard_value(int cardValue) {
			card_value = cardValue;
		}

		public BeraCard(Context context) {
			super(context);
		}

		/**
		 * 翻回关闭状态
		 * 
		 * @author:beralee
		 */
		public void setDefault() {
			this.setImageResource(default_cardimage);
			card_state = 0;
		}

		/**
		 * 打开状态
		 * 
		 * @author:beralee
		 */
		public void setOpen() {
			this.setImageResource(card_value);
			card_state = 1;
		}

		public void update() {
			postInvalidate();
		}

		/**
		 * 旋转动画
		 * 
		 * @param card
		 * @return
		 * @author:beralee
		 */
		public AnimationDrawable getFrameAni(BeraCard card) {
			AnimationDrawable ani = new AnimationDrawable();
			ani.setOneShot(true);
			card.setBackgroundDrawable(ani);
			card_state = 0;
			return ani;
		}

		// handle the location of the explosion
		public void setLocation(int top, int left) {
			this.setFrame(left, top, left + 40, top + 40);
		}

		/**
		 * @return the card_state
		 */
		public int getCard_state() {

			return card_state;
		}

		/**
		 * @return the card_value
		 */
		public int getCard_value() {
			return card_value;
		}

	}

	class SimpleListener implements OnTouchListener {

		public boolean onTouch(View v, MotionEvent event) {
			if (isdoing) {
				return false;
			}
			isdoing = true;
			if (!start) {
				start = true;
				from = System.currentTimeMillis();
			}

			BeraCard card = (BeraCard) v;
			touchingcard = card;
			switch (state) {
			case 1:

				if (card.getCard_state() == 0) {
					if (Config.OPEN_BGM)
						music_card.start();
					// 关闭状态下翻开卡片并
					card.setOpen();
					state = 2;
					waitcard = card;
					// Animation an = new AlphaAnimation(1.0f,0.5f);
					// an.setFillAfter(true);
					// an.setDuration(2000);
					// an.setRepeatCount(-1);
					// an.initialize(10, 10, 10, 10);
					// v.startAnimation(an);
				}
				isdoing = false;
				break;
			case 2:
				if (card.getCard_state() == 0) {
					// 关闭状态下翻开卡片并

					if (waitcard != null && card.getCard_value() == waitcard.getCard_value()) {
						if (Config.OPEN_BGM)
							music_success.start();
						// 成功了 打开就好
						card.setOpen();
						// card.startAnimation(an);
						isdoing = false;
						opened_card += 2;
						if (opened_card == Config.CARD_NUM) {
							// 结束了。
							if (Config.OPEN_MUSIC) {
								MainMenu.music_song.stop();
								MainMenu.music_song.release();
								MainMenu.music_song = MediaPlayer.create(BitmapTouch.this, R.raw.win);
								MainMenu.music_song.start();
							}
							to = System.currentTimeMillis();
							time=to-from;
							switch (Config.MODE) {
							case 1:
								showDialog(1);
								break;
							case 0:
								if (Config.Point == Config.MaxPoint) {
									mDbHelper.updateValue("maxpoint",""+Config.MaxPoint);
									Config.CAN_CHOOSE_Point = Config.MaxPoint;
									showDialog(3);
								} else {
								//TODO 判断如果当前关卡的时间小于初始时间则不让过关
									Integer pointinitvalue=Config.pointvaluemap.get(new Integer(Config.Point ));
									if(time>pointinitvalue){
										showDialog(4);
									}else{
										Cursor cr = mDbHelper.fetchValue("maxpoint");
										String maxpoint = cr.getString(cr.getColumnIndexOrThrow("value"));
										if (Integer.valueOf(maxpoint) <= Config.Point) {
											// 提高最大关卡数
											mDbHelper.updateValue("maxpoint", "" +( Config.Point+1));
											Config.CAN_CHOOSE_Point = Config.Point+1;
											
										}
										showDialog(2);
									}
									}
								break;
							}
						}
					} else {
						mHandler.post(new myThread());
					}
					state = 1;
				} else {
					isdoing = false;
				}
				break;
			}

			return false;
		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		// 挑战模式成功后
		case 1:
			return new AlertDialog.Builder(BitmapTouch.this)
					.setTitle(this.getResources().getText(R.string.gongxi)).setMessage("").setPositiveButton(
							this.getResources().getText(R.string.button_restart),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									tl.removeAllViews();
									// 初始化运行数据
									initData();
									// 初始化界面数据
									initImage();

									setContentView(rl);
								}
							}).setNegativeButton(this.getResources().getText(R.string.button_mainmenu),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									/*Intent intent = new Intent();
									intent.setClass(BitmapTouch.this, MainMenu.class);
									startActivity(intent);*/
									BitmapTouch.this.finish();
								}
							}).create();
			// 过关模式成功后
		case 2:
			return new AlertDialog.Builder(BitmapTouch.this)
					.setTitle(this.getResources().getText(R.string.gongxi)).setMessage("").setPositiveButton(
							this.getResources().getText(R.string.button_nextlevel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									tl.removeAllViews();
									Config.Point++;

									MapUtil.configByPoint();
									// 初始化运行数据
									initData();
									// 初始化界面数据
									initImage();

									setContentView(rl);
								}
							}).setNeutralButton(this.getResources().getText(R.string.button_restart),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									tl.removeAllViews();

									MapUtil.configByPoint();
									// 初始化运行数据
									initData();
									// 初始化界面数据
									initImage();

									setContentView(rl);
								}
							}).setNegativeButton(this.getResources().getText(R.string.button_mainmenu),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									/*
									 * Intent intent = new Intent();
									 * intent.setClass(BitmapTouch.this,
									 * MainMenu.class); startActivity(intent);
									 * BitmapTouch.this.finish();
									 */
									BitmapTouch.this.setResult(10);
									BitmapTouch.this.finish();
								}
							}).create();

		case 3:
			return new AlertDialog.Builder(BitmapTouch.this)
					.setTitle(this.getResources().getText(R.string.gongxi)).setNeutralButton(
							this.getResources().getText(R.string.button_restart),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									tl.removeAllViews();
									MapUtil.configByPoint();
									// 初始化运行数据
									initData();
									// 初始化界面数据
									initImage();

									setContentView(rl);
								}
							}).setPositiveButton(this.getResources().getText(R.string.button_mainmenu),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									/*
									 * Intent intent = new Intent();
									 * intent.setClass(BitmapTouch.this,
									 * MainMenu.class); startActivity(intent);
									 */
									BitmapTouch.this.finish();
								}
							}).create();
		case 4:
			return new AlertDialog.Builder(BitmapTouch.this)
					.setTitle(this.getResources().getText(R.string.henyihan)).setMessage("").setNeutralButton(
							this.getResources().getText(R.string.button_restart),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									tl.removeAllViews();
									MapUtil.configByPoint();
									// 初始化运行数据
									initData();
									// 初始化界面数据
									initImage();

									setContentView(rl);
								}
							}).setPositiveButton(this.getResources().getText(R.string.button_mainmenu),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									/*
									 * Intent intent = new Intent();
									 * intent.setClass(BitmapTouch.this,
									 * MainMenu.class); startActivity(intent);
									 */
									BitmapTouch.this.finish();
								}
							}).create();
		}

		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		
		switch (id) {
		case 1:
			AlertDialog timeDialog1 = (AlertDialog) dialog;
			Cursor cr = mDbHelper.fetchValue("callent");
			String callent = cr.getString(cr.getColumnIndexOrThrow("value"));
			long oldtime = Long.valueOf(callent).longValue();
			if (oldtime > time) {
				mDbHelper.updateValue("callent", "" + time);
				// 打破记录
				timeDialog1.setMessage(this.getResources().getText(R.string.newrecord)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.second)+ this.getResources().getText(R.string.youcanupload));
				mDbHelper.updateValue("canupdate", "1");
			} else {
				timeDialog1.setMessage(this.getResources().getText(R.string.norecord1)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.norecord2)
						+ format.format((double) Double.valueOf(oldtime) / 1000)
						+ this.getResources().getText(R.string.comeon));
			}
			break;
		case 2:
			AlertDialog timeDialog2 = (AlertDialog) dialog;
			Cursor pointcr = mDbHelper.fetchValue("point" + Config.Point);
			String pointvalue = pointcr.getString(pointcr.getColumnIndexOrThrow("value"));
			long pointoldtime = Long.valueOf(pointvalue).longValue();
			if (pointoldtime > time) {
				mDbHelper.updateValue("point" + Config.Point, "" + time);
				// 打破记录
				timeDialog2.setMessage(this.getResources().getText(R.string.newrecord)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.second));
			} else {
				timeDialog2.setMessage(this.getResources().getText(R.string.norecord1)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.norecord2)
						+ format.format((double) Double.valueOf(pointoldtime) / 1000)
						+ this.getResources().getText(R.string.comeon));
			}
			break;
		case 3:
			AlertDialog timeDialog3 = (AlertDialog) dialog;
			Cursor point8 = mDbHelper.fetchValue("point8");
			String pointvalue8 = point8.getString(point8.getColumnIndexOrThrow("value"));
			long pointoldtime8 = Long.valueOf(pointvalue8).longValue();
			if (pointoldtime8 > time) {
				mDbHelper.updateValue("point" + Config.Point, "" + time);
				// 打破记录
				timeDialog3.setMessage(this.getResources().getText(R.string.missioncmplete_newrecord)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.second));
			} else {
				timeDialog3.setMessage(this.getResources().getText(R.string.missioncmplete_norecord1)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.missioncmplete_norecord2)
						+ format.format((double) Double.valueOf(pointoldtime8) / 1000)
						+ this.getResources().getText(R.string.comeon));
			}
			break;
		case 4:
			Integer pointinitvalue=Config.pointvaluemap.get(new Integer(Config.Point ));
			AlertDialog timeDialog4 = (AlertDialog) dialog;
			timeDialog4.setMessage(this.getResources().getText(R.string.henyihanmsg)
						+ format.format((double) Double.valueOf(time) / 1000)
						+ this.getResources().getText(R.string.henyihanneed)
						+ format.format((double) Double.valueOf(pointinitvalue) / 1000)
						+ this.getResources().getText(R.string.comeon));
			
			break;
		default:
			break;
		}
		super.onPrepareDialog(id, dialog);
	}

	class myThread implements Runnable {
		public void run() {
			if (Config.OPEN_BGM)
				music_fail.start();
			touchingcard.setOpen();
			touchingcard.update();
			mHandler.postDelayed(new myThread2(), 400);

		}
	}

	class myThread2 implements Runnable {
		public void run() {
			touchingcard.setDefault();
			touchingcard.update();
			waitcard.setDefault();
			waitcard.update();
			waitcard = null;
			isdoing = false;
			/*
			 * Message message2 = new Message(); message2.what =
			 * BitmapTouch.GUIUPDATEIDENTIFIER2;
			 * BitmapTouch.this.myHandler.sendMessage(message2);
			 */
		}
	}
	   @Override
	    protected void onPause() {
	        super.onPause();
	    	if (Config.OPEN_MUSIC) {
				MainMenu.music_song.release();
			}
	    }
	    
	    @Override
	    protected void onResume() {
	        super.onResume();
	        /*if (Config.OPEN_MUSIC) {
				MainMenu.music_song = MediaPlayer.create(this, R.raw.music1);
				MainMenu.music_song.setLooping(true);
				MainMenu.music_song.start();
			}*/
	    }
}